package com.weilele.mvvm.utils.glide

import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.ImageViewTarget
import com.bumptech.glide.request.target.Target
import com.weilele.mvvm.utils.safeGet
import java.io.File

/**
 * 设置图片
 */
inline fun ImageView.setImageAny(
    load: Any?,
    requestManagerBlock: ((RequestBuilder<Drawable>) -> RequestBuilder<Drawable>) = { it }
): ImageViewTarget<Drawable>? {
    val manager = Glide.with(this)
    if (load == null) {
        manager.clear(this)
        return null
    }
    if (load is String && load.isBlank()) {
        manager.clear(this)
        return null
    }
    return Glide.with(this).execute({
        it.asDrawable()
            .let { build ->
                requestManagerBlock.invoke(
                    when (load) {
                        is String -> build.load(load)
                        is File -> build.load(load)
                        is Int -> build.load(load)
                        is Uri -> build.load(load)
                        is ByteArray -> build.load(load)
                        is Bitmap -> build.load(load)
                        is Drawable -> build.load(load)
                        else -> build.load(load)
                    }
                )
            }
    }) {
        it.into(this)
    }.safeGet()
}

/**
 * 设置圆形图片
 */
inline fun ImageView.setImageCircleCrop(
    load: Any?,
    requestManagerBlock: ((RequestBuilder<Drawable>) -> RequestBuilder<Drawable>) = { it }
): ImageViewTarget<Drawable>? {
    return this.setImageAny(load) {
        requestManagerBlock(it.apply(RequestOptions.bitmapTransform(CircleCrop())))
    }
}

/**
 * 设置圆角图片
 */
inline fun ImageView.setImageRoundedCorners(
    load: Any?,
    roundingRadius: Int,
    requestManagerBlock: ((RequestBuilder<Drawable>) -> RequestBuilder<Drawable>) = { it }
): ImageViewTarget<Drawable>? {
    return this.setImageAny(load) {
        requestManagerBlock(
            it.apply(
                RequestOptions.bitmapTransform(
                    RoundedCorners(
                        roundingRadius
                    )
                )
            )
        )
    }
}

/**
 * 最基础架构
 */
inline fun <TranscodeType, IntoTarget : Target<TranscodeType>> RequestManager.execute(
    requestManagerBlock: ((RequestManager) -> RequestBuilder<TranscodeType>),
    requestBuilderBlock: ((RequestBuilder<TranscodeType>) -> IntoTarget),
): IntoTarget {
    return requestBuilderBlock(requestManagerBlock(this))
}